import 'package:flutter/material.dart';
import 'package:jd_flutter/base/foundation/flutter_extension.dart';
import 'package:photo_view/photo_view_gallery.dart';

import '../../router/router_util.dart';
import '../../utils/loading_util.dart';

class PreviewImagePage extends StatefulWidget {
  final PageController pageController;
  final List<ImageProvider> imageProvider;
  final ValueNotifier<String> _currentIndexValueNotifier;
  final int index;

  PreviewImagePage({
    super.key,
    this.index = 0,
    required this.imageProvider,
  })  : _currentIndexValueNotifier =
            ValueNotifier('${index + 1}/${imageProvider.length}'),
        pageController = PageController(initialPage: index);

  @override
  State<PreviewImagePage> createState() => _PreviewImagePageState();
}

class _PreviewImagePageState extends State<PreviewImagePage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  Color backColor = Colors.black;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backColor,
      body: Stack(children: <Widget>[
        PhotoViewGallery.builder(
          pageController: widget.pageController,
          itemCount: widget.imageProvider.length,
          backgroundDecoration: BoxDecoration(
            color: backColor,
          ),
          loadingBuilder: (BuildContext context, ImageChunkEvent? event) =>
              kLoadingView,
          onPageChanged: (index) => widget._currentIndexValueNotifier.value =
              '${index + 1}/${widget.imageProvider.length}',
          builder: (BuildContext context, int index) =>
              PhotoViewGalleryPageOptions(
            imageProvider: widget.imageProvider[index],
            onTapUp: (context, details, controllerValue) {
              RouterUtil.pop(context);
            },
          ),
        ),
        ValueListenableBuilder(
          valueListenable: widget._currentIndexValueNotifier,
          builder: (BuildContext context, String value, Widget? child) {
            return SafeArea(
                child: Container(
              width: context.width,
              height: 44,
              alignment: Alignment.center,
              child: Text(
                value,
                style: const TextStyle(color: Colors.white),
              ),
            ));
          },
        ),
      ]),
    );
  }
}
